package com.elite.groovy.callback

import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.util.EliteBean
import com.elite.groovy.kh.LogToDB
import com.elite.groovy.util.Util
import net.sf.json.JSONArray
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import org.springframework.jdbc.core.JdbcTemplate
import net.sf.json.JSONObject;
import com.elite.groovy.kh.KHUtil

/**
 * @Title:同步乐购乐销客户数据
 * @Description:⽤户数据同步/API
 * @Param:
 * @return:
 * @Author: TaoHao*
 * @Date: 2023/6/30
 */

public class apiSyncLglxCustomer implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiSyncLglxCustomer.class);

    private String charset = "utf-8"; //设置字符集
    private int timeout = 3600000; //设置请求超时时间
    private int enableSSLflag = 0;
    private String insertString = "";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        //获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        //初始化返回参数
        JSONObject resultJson = null;
        String result = "";
        //接收客户端调用参数
        String callJson = "";
        //获取接口请求信息
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }
        log.info("[调用请求信息]:" + callJson);

        String reqUrl = "";
        // 分页参数
        int pageSize = 300; //每页获取条数
        int page = 0;
        boolean hasMoreData = true;
        try {
            log.debug("【自动获取乐购乐销客户资料】-开始");
            String custUrl = KHDBConfig.getAPIURL(eliteBean, "LGLX_Customer");
            Boolean first;
            Integer totalPages;
            Boolean last;
            while (hasMoreData) {
                long t_startTime = System.currentTimeMillis();
                reqUrl = custUrl + "?page=" + page + "&size=" + pageSize;
                try {
                    String custResult = Util.doHttpGet(reqUrl, "UTF-8", timeout, enableSSLflag);
                    log.debug("apiSyncGLXCustomer调用结果：" + custResult + "调用耗时：" + (System.currentTimeMillis() - t_startTime));

                    //结果解析
                    JSONObject ReJson = JSONObject.fromObject(custResult);
                    //获取页码、条数相关信息
                    Integer numberOfElements = KHUtil.GetSFJV(ReJson, "numberOfElements").toInteger(); //当前页获取的数据条数
                    first = KHUtil.GetSFJV(ReJson, "first").toBoolean(); //是否首页
                    last = KHUtil.GetSFJV(ReJson, "last").toBoolean(); //是否最后一页
                    totalPages = KHUtil.GetSFJV(ReJson, "totalPages").toInteger(); //总页数
                    Integer totalElements = KHUtil.GetSFJV(ReJson, "totalElements").toInteger(); //总条数
                    log.debug("返回页码结果解析,当前页条数" + numberOfElements + "|是否首页：" + first + "|是否最后页：" + last + "|总页数：" + totalPages + "|当前页：" + page + "|总条数：" + totalElements);

                    //获取业务信息并处理
                    if (numberOfElements > 0) {
                        //获取到json数组
                        JSONArray custlistArr = ReJson.getJSONArray("content");
                        int custlistArrSize = custlistArr.size();
                        log.debug("当前页码获取条数" + custlistArrSize);
                        //解析字段内容
                        int insert_count=0;//新增条数
                        int update_count=0;//修改条数
                        for (int j = 0; j < custlistArrSize; j++) {
                            JSONObject customerJson = custlistArr.getJSONObject(j);
                            String id = KHUtil.GetSFJV(customerJson, "id"); //客户ID
                            String code = KHUtil.GetSFJV(customerJson, "code"); //客户编码
                            String name = KHUtil.GetSFJV(customerJson, "name"); // 客户名称
                            String marketAreaId = KHUtil.GetSFJV(customerJson, "marketAreaId");//市场区域ID
                            String marketAreaCode = KHUtil.GetSFJV(customerJson, "marketAreaCode");//市场区域编码
                            String marketAreaName = KHUtil.GetSFJV(customerJson, "marketAreaName"); //市场区域名称
                            String customerCategoryId = KHUtil.GetSFJV(customerJson, "customerCategoryId") //客户分类ID
                            String customerCategoryCode = KHUtil.GetSFJV(customerJson, "customerCategoryCode") //客户分类编码
                            String customerCategoryName = KHUtil.GetSFJV(customerJson, "customerCategoryName") //客户分类名称
                            String channelTypeId = KHUtil.GetSFJV(customerJson, "channelTypeId") //渠道类型ID
                            String channelTypeCode = KHUtil.GetSFJV(customerJson, "channelTypeCode"); //渠道类型编码
                            String channelTypeName = KHUtil.GetSFJV(customerJson, "channelTypeName") //渠道类型名称
                            String countryId = KHUtil.GetSFJV(customerJson, "countyId"); //国家ID
                            String countryCode = KHUtil.GetSFJV(customerJson, "countyCode");//国家编码
                            String countryName = KHUtil.GetSFJV(customerJson, "countyName");//国家名称
                            String provinceId = KHUtil.GetSFJV(customerJson, "provinceId");//省份ID
                            String provinceName = KHUtil.GetSFJV(customerJson, "provinceName");//省份名称
                            String provinceCode = KHUtil.GetSFJV(customerJson, "provinceCode");//省份编码
                            String cityId = KHUtil.GetSFJV(customerJson, "cityId");//城市ID
                            String cityCode = KHUtil.GetSFJV(customerJson, "cityCode");//城市编码
                            String cityName = KHUtil.GetSFJV(customerJson, "cityName");//城市名称
                            String countyId = KHUtil.GetSFJV(customerJson, "countyId") //区域ID
                            String countyName = KHUtil.GetSFJV(customerJson, "countyName") //区域名称
                            String countyCode = KHUtil.GetSFJV(customerJson, "countyCode") //区域编码
                            String detailAddr = KHUtil.GetSFJV(customerJson, "detailAddr") //详细地址
                            String tel = KHUtil.GetSFJV(customerJson, "tel");//联系⽅式

                            //判断ID是否存在 不存在新增  存在更新
                            String isString2 = '''select id from lglx_customer  where code= ? ''';
                            List<Map<String, Object>> selelctList2 = jt.queryForList(isString2, code);

                            if (selelctList2.size() > 0) {
                                String UpdateSql2 = '''UPDATE lglx_customer SET code =?,name = ?,marketAreaId = ?,marketAreaCode =?,marketAreaName =?,customerCategoryId = ?,customerCategoryCode = ?,customerCategoryName = ?,channelTypeId = ?,channelTypeCode = ?,channelTypeName =?,countryId = ?,countryCode = ?,countryName =?,provinceId = ?,provinceName = ?,provinceCode = ?,cityId = ?,cityCode = ?,cityName = ?,countyId = ?,countyName = ?,countyCode = ?,detailAddr = ?,tel = ?,Sync_time = now() WHERE code = ?''';
                                int execute_update=jt.update(UpdateSql2, code, name, marketAreaId, marketAreaCode, marketAreaName, customerCategoryId, customerCategoryCode, customerCategoryName, channelTypeId, channelTypeCode, channelTypeName, countryId, countryCode, countryName, provinceId, provinceName, provinceCode, cityId, cityCode, cityName, countyId, countyName, countyCode, detailAddr, tel, code);
                                update_count=update_count+execute_update;
                            }else{
                                String insertSql = '''insert into  lglx_customer(rec_guid,id,code,name,marketAreaId,marketAreaCode,marketAreaName,customerCategoryId,customerCategoryCode,customerCategoryName,channelTypeId,channelTypeCode,channelTypeName,countryId,countryCode,countryName,provinceId,provinceName,provinceCode,cityId,cityCode,cityName,countyId,countyName,countyCode,detailAddr,tel,sync_time,createddate) values(uuid(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,now(),now())''';
                                int execute_insert=jt.update(insertSql, id, code, name, marketAreaId, marketAreaCode, marketAreaName, customerCategoryId, customerCategoryCode, customerCategoryName, channelTypeId, channelTypeCode, channelTypeName, countryId, countryCode, countryName, provinceId, provinceName, provinceCode, cityId, cityCode, cityName, countyId, countyName, countyCode, detailAddr, tel);
                                insert_count=insert_count+execute_insert;
                            }
                        }
                        log.debug("本组新增数据条数" + insert_count);
                        log.debug("本组更新数据条数" + update_count);

                    }
                    // 检查是否还有更多数据，不是最后一页并且页码小于返回的总页数-继续执行获取下一页
                    log.debug("当前是否最后页码：" + last + "|当前页码：" + page + "|总页码：" + totalPages);
                    if (!last && page < totalPages) {
                        hasMoreData = true;//继续执行下一页
                        // 增加页码
                        page++
                    } else {
                        hasMoreData = false;//停止执行
                    }
                    log.debug("是否继续执行：" + hasMoreData);
                } catch (Exception err1) {

                    if (!last && page < totalPages) {
                        hasMoreData = true;//继续执行下一页
                        // 增加页码
                        page++;
                    } else {
                        result = "0";
                        hasMoreData = false;//停止执行
                    }
                    log.debug("返回结果:" + result);
                    log.debug("返回结果解析异常:" + err1);
                }
            }
            result = "1";

        } catch (Exception err2) {
            result = "0";
            log.debug("Exception Error:", err2);
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "同步乐购乐销客户资料接口", "apiSyncGLXCustomer", resultJson.toString(), reqUrl, (System.currentTimeMillis() - startTime).toString(), "");
        }
        return result;
    }
}